package bootstrap

import (
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/container"
	"grpc.getaway.adminspro.padmins.com/internal/api/module/admin/middleware"
	"grpc.getaway.adminspro.padmins.com/internal/api/utils"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/request"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/response"
	utils2 "grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	"grpc.getaway.adminspro.padmins.com/pkg/support/log"
	"net/http"
	"os"
	"time"
)

func Handler(w http.ResponseWriter, r *http.Request) {
	t := time.Now()
	// 设置开始时间
	ctx := utils2.WithExtraRuntime(r.Context(), utils2.Runtime(t))
	// 设置TraceId
	ctx = utils2.WithExtraTraceId(ctx, utils2.TraceId(fmt.Sprintf("%s%d", utils2.Md5(t.String()), os.Getpid())))
	// 设置Log
	ctx = log.WithExtraLog(ctx, "api-admin")

	Message := &utils.Message{}
	Message.SetStartTime(t)
	c := &container.Context{
		Request:         request.NewHttpRequest(r),
		Response:        response.NewHttpResponse(w),
		ResponseMessage: Message,
		Auth:            &container.Auth{},
		Logger:          log.WithContext(ctx),
	}

	// 设置日志中间件
	c.SetMiddleware(middleware.RequestLogMiddleware)
	// 设置跨域中间件
	c.SetMiddleware(middleware.CorsMiddleware)
	// 设置鉴权中间件
	c.SetMiddleware(middleware.PermissionMiddleware)
	c.SetContext(ctx)
	run(c)
}
